package com.cloud.securityoauth2client1.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;

import java.util.Map;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableOAuth2Sso
@Order(-20)
public class ClientWebsecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
     /*   http.antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/success**"*//*,"/login**"*//*)
//                .anyRequest()
                .permitAll()
                .anyRequest()
                .authenticated();*/

        http.antMatcher("/**").authorizeRequests()
                .anyRequest().authenticated()
//                .antMatchers("/success/**").permitAll()
        .and().cors()
        .and().csrf().disable();
    }

    /**
     * https://blog.csdn.net/u011317663/article/details/82355195
     * @param parameters
     * @param currentUri
     * @return
     */
    @Bean(name = "accessTokenRequest")
    @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
    protected AccessTokenRequest accessTokenRequest(@Value("#{request.parameterMap}")
                                                            Map<String, String[]> parameters, @Value("#{request.getAttribute('currentUri')}")
                                                            String currentUri){
        DefaultAccessTokenRequest defaultAccessTokenRequest = new DefaultAccessTokenRequest();
        defaultAccessTokenRequest.setCurrentUri(currentUri);
        defaultAccessTokenRequest.set("redirect_uri","http://localhost:9502/success");
        return defaultAccessTokenRequest;
    }

}
